import { app, shell, BrowserWindow, dialog } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset';
import userOn from './userOn';//用户交互js
import trayUser from './trayUser';//用户托盘菜单设置js
import items from './items';//整个项目运行的类


app.commandLine.appendSwitch('ignore-certificate-errors');

let tray = null;//托盘

let mainWindow = null;

function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1100,
    minWidth: 850,
    height: 700,
    minHeight: 550,
    show: false,//默认启动窗口是否隐藏的
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? {
      icon
    } : {
      // win环境
      icon,
      closable: true,
      frame: false,//创建无框架窗口
    }),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      webSecurity: false//关闭跨域限制
    }
  });

  // 监听窗口关闭事件
  mainWindow.on('close', (event) => {
    // 阻止窗口关闭
    event.preventDefault();
    // 默认只隐藏
    mainWindow.hide();
  });





  try {
    let itemsClass = items(mainWindow);//运行项目类
    tray = trayUser(mainWindow, itemsClass);//托盘图标设置

    userOn(mainWindow, itemsClass);//注入用户交互js

  } catch (error) {
    dialog.showMessageBox({
      type: 'error',
      buttons: ['OK'],
      message: error.message,
    });
  }

  mainWindow.on('ready-to-show', () => {
    // 等页面渲染完成 再显示
    mainWindow.show();
  });


  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url);
    return { action: 'deny' }
  });

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL']);
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'));
  }


  // mainWindow.webContents.openDevTools();//打开控制台

}

// 检查是否已经有应用在运行了
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
  app.exit();
} else {

  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 当运行第二个实例时,将会聚焦到myWindow这个窗口
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore();
      if (!mainWindow.isVisible()) mainWindow.show();
      mainWindow.focus();
    }
  });

  // This method will be called when Electron has finished
  // initialization and is ready to create browser windows.
  // Some APIs can only be used after this event occurs.
  app.whenReady().then(() => {
    // Set app user model id for windows
    electronApp.setAppUserModelId('cn.wyouw.cn.block');

    // Default open or close DevTools by F12 in development
    // and ignore CommandOrControl + R in production.
    // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
    app.on('browser-window-created', (_, window) => {
      optimizer.watchWindowShortcuts(window)
    });

    createWindow();


    app.on('activate', function () {
      // On macOS it's common to re-create a window in the app when the
      // dock icon is clicked and there are no other windows open.
      if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
  });

  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      app.quit()
    }
  })

  // 销毁托盘
  app.on('before-quit', () => {
    if (tray) {
      tray.destroy();
    }
  });

}

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
